import hashlib
from datetime import datetime
from injector import inject
from dataclasses import dataclass
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
from werkzeug.datastructures import FileStorage
from .upload_file_service import UploadFileService
from internal.exception import FailException
from internal.entity.upload_entity import ALLOW_DOCUMENT_EXTENSION, ALLOW_IMG_EXTENSION
import os
import uuid


@inject
@dataclass
class CosService:
    upload_file_service: UploadFileService

    @classmethod
    def getClient(cls):
        config = CosConfig(
            Region=os.getenv("REGION"),
            SecretId=os.getenv("SECRET_ID"),
            SecretKey=os.getenv("SECRET_KEY"),
            Token=None,
            Scheme=os.getenv("SCHEME")
        )
        client = CosS3Client(config)
        return client

    @classmethod
    def get_buket(cls):
        return os.getenv("BUKET_NAME")

    def upload_file(self, file: FileStorage, onlay_img: bool = False):
        client = self.getClient()
        buket_name = self.get_buket()
        file_name = file.filename
        extension = file_name.rsplit(".", 1)[-1] if "." in file_name else ""
        if extension.lower() not in (ALLOW_DOCUMENT_EXTENSION + ALLOW_IMG_EXTENSION):
            raise FailException(f"该扩展名{extension}不允许上传")
        if onlay_img and extension.lower() not in ALLOW_IMG_EXTENSION:
            raise FailException(f"该扩展名{extension}不允许上传，请上传正确的图片格式")
        f = file.stream.read()
        new_file_name = f"{uuid.uuid4()}.{extension}"
        now = datetime.now()
        upload_file_name = f"{now.year}/{now.month:02d}/{now.day:02d}/{new_file_name}"
        try:
            client.put_object(Bucket=buket_name, Body=f, Key=upload_file_name)
        except Exception as e:
            print(e)
            raise FailException("上传文件失败请稍后再试")
        return self.upload_file_service.upload_file(
            account_id="e2e2fd57-340d-4746-a89f-558fbca3af8f",
            name=new_file_name,
            key=upload_file_name,
            size=len(f),
            extension=extension,
            mime_type=file.mimetype,
            hash=hashlib.sha3_256(f).hexdigest(),
        )

    def get_img_url(self, key):
        buket_name = self.get_buket()
        region = os.getenv("REGION")
        scheme = os.getenv("SCHEME")
        doman = f"{scheme}://{buket_name}.cos.{region}.myqcloud.com"
        return f"{doman}/{key}"
